package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.apache.ibatis.annotations.Insert;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.convert.KeyspaceConfiguration;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IUserService userService;
    /**
     * 关注用户和取消关注，关注就是把当前用户的id和需要关注的用户id插入数据库
     * @param followUserId 需要关注的用户的id
     * @param isFollow 判断是关注还是取消关注， 前端传入true为关注， false为取消管住宿
     * @return
     */
    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        //1. 获取当前登录的用户
        Long userId = UserHolder.getUser().getId();
        String key = "follow:" + userId;
        //2、 判断关注还是取消关注
        if(isFollow) { //关注
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId); //当前需要关注的用户的id
            boolean isSuccess = save(follow);
            if(isSuccess) { //关注成功，加入redis,方便实现共同关注的功能
                stringRedisTemplate.opsForSet().add(key, followUserId.toString());
            }

        } else { //取关
            //3、取关， 删除数据， delete from tb_follow where user_id = ? and follow_user_id = ?
            boolean isSuccess = remove(new QueryWrapper<Follow>()
                    .eq("user_id", userId).eq("follow_user_id", followUserId));
            if(isSuccess) {
                //把该关注用户从redis中删除
                stringRedisTemplate.opsForSet().remove(key, followUserId.toString());
            }
        }
        return Result.ok();
    }

    /**
     * 判断当前登录用户是否关注了当前查看的用户
     * @param followUserId
     * @return
     */
    @Override
    public Result isFollow(Long followUserId) {
        //1、获取登录用户
        Long userId = UserHolder.getUser().getId();
        //2、查询用户是否关注 select count(*) from tb_follow where user_id = ? and follow_user_id = ?
        Integer count = query().eq("user_id", userId).eq("follow_user_id", followUserId).count();
        //3、判断返回结果，大于0表示还有关注
        return Result.ok(count > 0);
    }

    /**
     * 共同关注： 当前登录用户和查看用户的共同关注的好友，通过redis的求交集，两个人的所有关注的用户的交集，就是共同关注了
     *  sinter s1 s2 求s1和s2两个用户的共同关注的用户
     * @param otherUserId 当前查看的用户的id
     * @return
     */
    @Override
    public Result followCommons(Long otherUserId) {
        //1、获取当前登录的用户
        Long userId = UserHolder.getUser().getId();
        String key = "follow:" + userId;
        //2、求交集
        String key2 = "follow:" + otherUserId;
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key, key2); //所有交集的id(String类型)
        System.out.println("String :" + intersect);
        if(intersect == null || intersect.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        //3、解析id为Long类型的
        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList()); //每一个转化为long类型，再收集成为list
        System.out.println("Long :" + ids);
        //4、根据这些共同用户的id查询出这些用户
        List<UserDTO> users = userService.listByIds(ids)//查询用户
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class)) //转化为userDTO
                .collect(Collectors.toList()); //收集成为list
        return Result.ok(users);
    }
}
